<template>
	<view class="recognize-page">
		<text class="recognize-title">识别图片场景中的水果</text>
		<image @click="openCamera" mode="scaleToFill" class="recognize-img" :src="imgUrl"></image>
		<button @click="uploadFile" class="upload-img" type="primary">文件识别</button>
		<view class="upload-img-name">显示文件名称
			<view class="delete">X</view>
		</view>
		<text class="upload-result">显示识别后的结果:{{result}}</text>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imgUrl: "../../static/icon/add_img.png",
				result:""
			}
		},
		methods: {
			// 打开相机或者相册
			openCamera() {
				let that = this
				// 选择从相册还是照相机中获取图像
				uni.chooseImage({
					count: 1,
					crop:{
						resize:true,
						width:28,
						height:28
					},
					success: function(res) {
						let filePath = res.tempFilePaths[0]
						that.imgUrl = filePath
					}
				});
			},
			//上传文件
			uploadFile() {
				let that = this
				uni.uploadFile({
					url: 'http://192.168.23.116:9000/upload', //仅为示例，非真实的接口地址
					filePath: that.imgUrl,
					name: 'the_file',
					formData: {
						'user': 'test'
					},
					success: (uploadFileRes) => {
						// console.log(uploadFileRes.data);
						//需要对string结果进行JSON解析成object对象
						let data = JSON.parse(uploadFileRes.data)
						// 设置结果
						that.result = data.result
					},
					fail: (error) => {
						console.log(error);
					}
				});
			}
		}
	}
</script>

<style lang="less" scoped>
	.recognize-page {
		padding: 10rpx;

		.recognize-title {
			display: block;
			border-left: 10rpx solid #007AFF;
			padding-left: 10rpx;
			margin: 10rpx 0;
		}

		.recognize-img {
			display: block;
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 10rpx;
		}

		.upload-img-name {
			height: 60rpx;
			border: 2rpx solid #F5F5F5;
			border-radius: 10rpx;
			margin: 20rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			box-shadow: 0 10rpx 10rpx -5rpx #EBEBEB;
			position: relative;

			.delete {
				position: absolute;
				font-size: 30rpx;
				top: calc(50% - 15rpx);
				right: 20rpx;
			}
		}

		.upload-result {
			font-size: 40rpx;
		}
	}
</style>